package com.example.baselib

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.json.JSONObject
import retrofit2.Response


/**
 * @author sxygsj.
 * @creat time 2020/4/13 14:03.
 * @description [网上找的网络请求base]
 * @chang time 2020/4/13 14:03.
 * @chang describe []
 */
open class BaseRepository {

    suspend fun <T : Any> request(call: suspend () -> Response<T>): Response<T> {
        return withContext(Dispatchers.IO) {
            delay(300)
            call.invoke() //请求方法执行]
        }.apply {
            //由于可能服务端将错误信息放在errorbody中，做下处理
            //正常请求可以通过code，msg 做判断，由于login接口没有，所以不好处理，只能自定义Gson解析
            //see CustomGsonConverterFactory
            if (code() != 200){
                var msg: String
                msg= errorBody()?.string().toString()
                Log.e("++++errorBody+++",msg)
                try {
                    val json = JSONObject(msg)
                    msg =  json.getString("message")
                }catch (e:Exception){
                }
                throw RequestException(msg)
            }
        }
    }

    class RequestException(msg: String = "请求错误") : Exception(msg)
}